<template>
  <div class="contanier">
    <div class="contanier-title">试卷管理</div>
    <search-form>
      <template v-slot:formLeft>
        <el-form :inline="true" :model="userFormLine" class="demo-form-inline">
          <el-row>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="试卷名称" label-width="80px">
                  <el-input v-model="userFormLine.fullName" placeholder="请输入试卷名称"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple-light">
                <el-form-item label="出题方式" label-width="80px">
                  <el-select v-model="userFormLine.paperType" placeholder="请选择试卷类型" label-width="80px">
                    <el-option label="手动出题" value="1"></el-option>
                    <el-option label="自动出题" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="试卷编号" label-width="100px">
                  <el-input v-model="userFormLine.enCode" placeholder="请输入试卷编号"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12">
              <div class="grid-content bg-purple-light">
                <el-form-item label="试卷开放权限" label-width="100px">
                  <el-select v-model="userFormLine.paperrandomVersion" placeholder="请选择试卷开放权限">
                    <el-option label="大众用户" value="1"></el-option>
                    <el-option label="培训考试用户" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col> -->
          </el-row>
        </el-form>
      </template>
      <template v-slot:formRight>
        <div class="formRight-btn">
          <el-button icon="el-icon-refresh" class="overPosBtn" @click="resetForm">重 置</el-button>
          <el-button type="primary" @click="onSubmit" icon="el-icon-search" class="set-col-btn">查 询</el-button>
        </div>
      </template>
    </search-form>
    <div>
      <search-table>
        <template v-slot:daochu>
          <div class="set-table-right">
            <el-button icon="el-icon-my-add" @click="addTest">新增试卷</el-button>
            <el-button icon="el-icon-my-message" @click="handleExport" :loading="exporting">导 出</el-button>
          </div>
        </template>
        <template v-slot:biaoge>
          <template>
            <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
              @selection-change="handleSelectionChange" class="table-top" :header-cell-style="{
                backgroundColor: '#f5f7fa',
                color: '#606266',
              }">
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="试卷名称">
                <template slot-scope="scope">{{ scope.row.fullName }}</template>
              </el-table-column>
              <el-table-column label="出题方式">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.paperType === '1'" type="success">手动出题</el-tag>
                  <el-tag v-if="scope.row.paperType === '2'" type="warning">自动出题</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="enCode" label="试卷编号">
              </el-table-column>
              <!-- <el-table-column prop="paperType" label="出题方式">
                <template slot-scope="scope">
                  <span v-if="scope.row.paperType === '1'">手动出题</span>
                  <span v-else-if="scope.row.paperType === '2'">自动出题</span>
                  <span v-else>--</span>
                </template>
              </el-table-column> -->
              <!-- <el-table-column prop="paperrandomVersion" label="试卷开放权限">
                <template slot-scope="scope">
                  <span v-if="scope.row.paperrandomVersion === '1'">大众用户</span>
                  <span v-else-if="scope.row.paperrandomVersion === '2'">培训考试用户</span>
                  <span v-else>--</span>
                </template>
              </el-table-column> -->
              <!-- <el-table-column prop="lastModifyTime" label="chuanchuan">
                <template slot-scope="scope">
                  <span v-if="scope.row.lastModifyTime">
                    {{ scope.row.lastModifyTime.split('T')[0] }} 至 {{ formatExpiryDate(scope.row.lastModifyTime) }}
                  </span>
                  <span v-else>--</span>
                </template>
              </el-table-column> -->
              <!-- <el-table-column prop="zt" label="状态">
                <template slot-scope="scope">
                  <el-switch 
                    v-model="scope.row.zt" 
                    active-color="#2265EE" 
                    inactive-color="#DBDFEA" 
                    :active-value="1"
                    :inactive-value="0"
                    @change="handleStatusChange(scope.row)">
                  </el-switch>
                </template>
              </el-table-column> -->
              <el-table-column fixed="right" label="操作" width="380">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="editRow(scope.$index, tableData)" type="text" icon="el-icon-edit"
                    size="small" class="set-table-btn set-table-btn-col">
                    编辑
                  </el-button>
                  <!-- <el-button @click.native.prevent="setsjsz(scope.$index, tableData)" type="text" icon="el-icon-setting"
                    size="small" class="set-table-btn set-table-btn-col">
                    试卷设置
                  </el-button> -->
                  <el-button @click.native.prevent="deleteRow(scope.$index, tableData)" type="text"
                    class="set-table-btn set-table-btn-col" icon="el-icon-document
                                        " size="small">
                    详情
                  </el-button>
                  <el-button @click.native.prevent="delRow(scope.$index, tableData)" type="text"
                    class="set-table-btn set-table-btn-col2" icon="el-icon-delete" size="small" style="color: #d91515">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </template>
        <template v-slot:fenye>
          <div class="set-table-pg-right">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </template>
      </search-table>
    </div>

    <!-- <el-dialog title="试题类型选择" :visible.sync="showSTLX" width="30%">
      <div class="tip">
        <div class="header">
          <ul class="header-ul">
            <li class="header-li" @click="chooseItem(1)">
              <img src="../../assets/images/xztt.png" alt="" />
              <p>选择题</p>
            </li>
            <li class="header-li" @click="chooseItem(2)">
              <img src="../../assets/images/pdt.png" alt="" />
              <p>判断题</p>
            </li>
            <li class="header-li" @click="chooseItem(3)">
              <img src="../../assets/images/wdt.png" alt="" />
              <p>问答题</p>
            </li>
            <li class="header-li" @click="chooseItem(4)">
              <img src="../../assets/images/tkt.png" alt="" />
              <p>填空题</p>
            </li>
          </ul>
        </div>
      </div>
    </el-dialog> -->
    <el-dialog title="试卷设置" :visible.sync="showsjsz" width="40%">
      <div class="tip">
        <div class="header">
          <el-form ref="sjform" :model="sjform" label-width="100px">
            <el-form-item label="试卷名称">
              <el-input v-model="sjform.fullName"></el-input>
            </el-form-item>
            <el-form-item label="试卷类型">
              <el-radio v-model="sjform.paperType" label="1">普通试卷</el-radio>
              <el-radio v-model="sjform.paperType" label="2">随机试卷</el-radio>
            </el-form-item>
            <el-form-item label="试卷开放权限">
              <el-select v-model="sjform.paperrandomVersion" placeholder="请选择试卷开放权限">
                <el-option label="全公司" value="1"></el-option>
                <el-option label="仅创建人" value="2"></el-option>
                <el-option label="部门/人员" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="试卷编号">
              <el-input v-model="sjform.enCode"></el-input>
            </el-form-item>
            <div class="sjform-tip">
              <i class="el-icon-warning-outline"></i>分值设置：系统判断总分必须等于100分
            </div>
            <el-table :data="tableData1" style="width: 100%">
              <el-table-column prop="singleScore" label="单选">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.singleScore" :min="0" :max="100" placeholder="请输入分值"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="multipleScore" label="多选">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.multipleScore" :min="0" :max="100" placeholder="请输入分值"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="judgeScore" label="判断题">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.judgeScore" :min="0" :max="100" placeholder="请输入分值"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="fillScore" label="填空题">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.fillScore" :min="0" :max="100" placeholder="请输入分值"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="questionScore" label="问答题">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.questionScore" :min="0" :max="100" placeholder="请输入分值"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="passScore" label="及格分数">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.passScore" :min="0" :max="100" placeholder="请输入分值"></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showsjsz = false">取 消</el-button>
        <el-button type="primary" @click="saveExamSettings">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="showTest" width="30%">
      <div class="tip">
        <div class="header">
          <div class="dia-txt">是否确认删除？</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showTest = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确认</el-button>
      </span>
    </el-dialog>
    <!-- <pdt :show="showPDT" @closeDrawer="closeDrawer"></pdt>
    <tkt :show="showTKT" @closeDrawer="closeDrawertkt"></tkt>
    <xzt :show="showXZT" @closeDrawer="closeDrawerxZt"></xzt>
    <wdt :show="showWDT" @closeDrawer="closeDrawerwdt"></wdt> -->
  </div>
</template>
<script>
import SearchForm from "@/components/search-form";
import SearchTable from "@/components/search-table";
import pdt from "./pdt";
import tkt from "./tkt";
import xzt from "./xzt";
import wdt from "./wdt";
import { getList, deleteExam, getDetail, Update, exportExecl } from "./api/exam";
// import { getList, deleteExam, getDetail, Update, exportExam } from "./api/exam";
export default {
  name: "UserManagement",
  components: {
    SearchForm,
    SearchTable,
    pdt,
    tkt,
    xzt,
    wdt,
  },
  data() {
    return {
      exporting: false,
      showTest: false,
      currentRow: null,
      tableData1: [{}],
      sjform: {},
      currentExamId: '',
      showsjsz: false,
      showPDT: false,
      showTKT: false,
      showXZT: false,
      showWDT: false,
      showSTLX: false,
      userFormLine: {
        fullName: "",
        paperType: "",
        categoryId: "",
        enCode: "",
        paperrandomVersion: "",
        orderByColumn: "createTime",
        isAsc: "desc"
      },
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
    };
  },
  created() {
    this.getTableList();
  },
  methods: {
    async setsjsz(index, row) {
      try {
        const res = await getDetail(row[index].id);
        if (res.code === 200) {
          this.currentExamId = row[index].id;
          // 设置表单数据
          this.sjform = {
            fullName: res.data.fullName || '',
            paperType: res.data.paperType || '1',
            paperrandomVersion: res.data.paperrandomVersion || '1',
            enCode: res.data.categoryId || ''
          };

          // 设置分值表格数据
          this.tableData1 = [{
            singleScore: res.data.singleScore || 0,
            multipleScore: res.data.multipleScore || 0,
            judgeScore: res.data.judgeScore || 0,
            fillScore: res.data.fillScore || 0,
            questionScore: res.data.questionScore || 0,
            passScore: res.data.passLine || 0
          }];

          this.showsjsz = true;
        } else {
          this.$message.error(res.msg || '获取试卷设置失败');
        }
      } catch (error) {
        console.error('获取试卷设置失败:', error);
        this.$message.error('获取试卷设置失败');
      }
    },
    async saveExamSettings() {
      try {
        // 验证总分是否为100
        const scores = this.tableData1[0];
        const totalScore = Number(scores.singleScore || 0) +
          Number(scores.multipleScore || 0) +
          Number(scores.judgeScore || 0) +
          Number(scores.fillScore || 0) +
          Number(scores.questionScore || 0);

        if (totalScore !== 100) {
          this.$message.error('总分必须等于100分');
          return;
        }

        // 构建更新参数
        const params = {
          id: this.currentExamId,
          fullName: this.sjform.fullName,
          paperType: this.sjform.paperType,
          categoryId: this.sjform.enCode,
          paperrandomVersion: this.sjform.paperrandomVersion,
          passLine: this.tableData1[0].passScore,
          myScore: totalScore,
          passScore: this.tableData1[0].passScore,
          singleScore: this.tableData1[0].singleScore,
          multipleScore: this.tableData1[0].multipleScore,
          judgeScore: this.tableData1[0].judgeScore,
          fillScore: this.tableData1[0].fillScore,
          questionScore: this.tableData1[0].questionScore,
          enabledMark: null,
          rules: [],
          questions: [],
          deleteMark: null
        };

        // 如果是自动出题，paperrandomVersion代表固定版本
        if (params.paperType == 2) {
          params.paperrandomVersion = 1;
        }

        const res = await Update(params);
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.showsjsz = false;
          this.getTableList(); // 刷新列表
        } else {
          this.$message.error(res.msg || '保存失败');
        }
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存失败');
      }
    },
    closeDrawer() {
      this.showPDT = false;
    },
    closeDrawertkt() {
      this.showTKT = false;
    },
    closeDrawerxZt() {
      this.showXZT = false;
    },
    closeDrawerwdt() {
      this.showWDT = false;
    },
    chooseItem(val) {
      switch (val) {
        case 1:
          this.showXZT = true;
          break;
        case 2:
          this.showPDT = true;
          break;
        case 3:
          this.showWDT = true;
          break;
        case 4:
          this.showTKT = true;
          break;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getTableList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTableList();
    },
    addTest() {
      this.$router.push({ 
        path: "/testAdd/index",
        query: { type: 'add' }
      });
    },
    async editRow(index, row) {
      try {
        const res = await getDetail(row[index].id);
        if (res.code === 200) {
          // 处理试题数据
          const questions = res.data.questions || [];
          // 导航到编辑页面，传递完整数据
          this.$router.push({ 
            path: "/testAdd/index",
            query: { 
              type: 'edit',
              id: row[index].id 
            },
            state: {
              questions: questions,
              formData: {
                fullName: res.data.fullName,
                paperType: res.data.paperType,
                passScore: res.data.passScore,
                passLine: res.data.passLine,
                myScore: res.data.myScore,
                description: res.data.description,
                intro: res.data.intro,
                categoryId: res.data.categoryId,
                enCode: res.data.enCode,
                paperrandomVersion: res.data.paperrandomVersion
              }
            }
          });
        } else {
          this.$message.error(res.msg || '获取试卷详情失败');
        }
      } catch (error) {
        console.error('获取试卷详情失败:', error);
        this.$message.error('获取试卷详情失败');
      }
    },
    async deleteRow(index, row) {
      try {
        const res = await getDetail(row[index].id);
        if (res.code === 200) {
          // 处理试题数据
          const questions = res.data.questions || [];
          // 导航到详情页面，传递完整数据
          this.$router.push({ 
            path: "/testAdd/index",
            query: { 
              type: 'detail',
              id: row[index].id 
            },
            state: {
              questions: questions,
              formData: {
                fullName: res.data.fullName,
                paperType: res.data.paperType,
                passScore: res.data.passScore,
                passLine: res.data.passLine,
                myScore: res.data.myScore,
                description: res.data.description,
                intro: res.data.intro,
                categoryId: res.data.categoryId,
                enCode: res.data.enCode,
                paperrandomVersion: res.data.paperrandomVersion
              }
            }
          });
        } else {
          this.$message.error(res.msg || '获取试卷详情失败');
        }
      } catch (error) {
        console.error('获取试卷详情失败:', error);
        this.$message.error('获取试卷详情失败');
      }
    },
    delRow(index, row) {
      this.$confirm('此操作将永久删除该试卷, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.confirmDelete(row[index].id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async confirmDelete(id) {
      if (!id) {
        this.$message.error('删除失败：未找到试卷ID');
        return;
      }
      
      try {
        const res = await deleteExam(id);
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.getTableList();
        } else {
          this.$message.error(res.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除失败:', error);
        this.$message.error('删除失败');
      }
    },
    getTableList() {
      const params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.userFormLine.fullName || this.userFormLine.enCode || null,
        paperType: this.userFormLine.paperType || null,
        categoryId: this.userFormLine.categoryId || null,
        paperrandomVersion: this.userFormLine.paperrandomVersion || null,
        // enCode: this.userFormLine.enCode || null,
        // orderByColumn: this.userFormLine.orderByColumn,
        // isAsc: this.userFormLine.isAsc
      };

      // 移除空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === null || params[key] === '') {
          delete params[key];
        }
      });

      getList(params).then(res => {
        if (res.code == 200) {
          this.tableData = (res.data.list || []).map(item => ({
            id: item.id || '',
            fullName: item.fullName || '--',
            paperType: item.paperType || '--',
            categoryId: item.categoryId || '--',
            enCode: item.enCode || '--',
            questionType: item.questionType || '--',
            paperrandomVersion: item.paperrandomVersion || '--',
            lastModifyTime: item.lastModifyTime || '',
            enabledMark: Number(item.enabledMark) || 0
          }));
          
          const pagination = res.data.pagination || {};
          this.total = parseInt(res.data.pagination.total);
          this.currentPage = parseInt(res.data.pagination.currentPage);
          this.pageSize = parseInt(res.data.pagination.pageSize);
        } else {
          this.$message.error(res.msg || '获取列表失败');
        }
      }).catch(error => {
        console.error('获取列表失败:', error);
        this.$message.error('获取列表失败');
      });
    },
    resetForm() {
      this.userFormLine = {
        fullName: "",
        paperType: "",
        categoryId: "",
        enCode: "",
        paperrandomVersion: "",
        orderByColumn: "createTime",
        isAsc: "desc"
      };
      this.currentPage = 1;
      this.getTableList();
    },
    onSubmit() {
      this.currentPage = 1;
      this.getTableList();
    },
    // 添加状态切换处理方法
    handleStatusChange(row) {
      console.log('状态切换:', row.id, row.zt);
      // TODO: 这里添加状态更新的接口调用
    },
    formatExpiryDate(lastModifyTime) {
      if (!lastModifyTime) return '--';
      try {
        // 将lastModifyTime转换为Date对象
        const modifyDate = new Date(lastModifyTime);
        // 添加10天
        const expiryDate = new Date(modifyDate.getTime() + 10 * 24 * 60 * 60 * 1000);
        // 格式化日期为 YYYY-MM-DD
        return expiryDate.toISOString().split('T')[0];
      } catch (error) {
        return '--';
      }
    },
    async handleExport() {
      let data = {
        ...this.userFormLine,
        currentPage: this.currentPage,
        pageSize: 10000,
      };
      let paras = "selectKey=fullName,paperType,enCode&dataType=0"
      exportExecl(paras,data).then(res => {
        if (res.code === 200) {
          this.jsbos.downloadFile(res.data.url);
        }
      })
      
      //   // 构建导出参数，包含当前的搜索条件
      //   const exportParams = {
      //     fullName: this.userFormLine.fullName || undefined,
      //     paperType: this.userFormLine.paperType || undefined,
      //     categoryId: this.userFormLine.categoryId || undefined,
      //     enCode: this.userFormLine.enCode || undefined,
      //     paperrandomVersion: this.userFormLine.paperrandomVersion || undefined
      //   };

      //   // 移除空值参数
      //   Object.keys(exportParams).forEach(key => {
      //     if (exportParams[key] === undefined || exportParams[key] === '') {
      //       delete exportParams[key];
      //     }
      //   });

      //   // 创建一个隐藏的 a 标签用于下载
      //   const link = document.createElement('a');
      //   link.style.display = 'none';
        
      //   // 假设后端导出接口为 /api/exam/export
      //   const baseUrl = process.env.VUE_APP_BASE_API || '';
      //   const queryString = Object.keys(exportParams)
      //     .map(key => `${key}=${encodeURIComponent(exportParams[key])}`)
      //     .join('&');
        
      //   link.href = `${baseUrl}/api/exam/export${queryString ? `?${queryString}` : ''}`;
      //   link.download = `试卷列表_${new Date().toLocaleDateString()}.xlsx`;
        
      //   document.body.appendChild(link);
      //   link.click();
      //   document.body.removeChild(link);
        
      //   this.$message.success('导出成功');
      // } catch (error) {
      //   console.error('导出失败:', error);
      //   this.$message.error('导出失败');
      // } finally {
      //   this.exporting = false;
      // }
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-icon-my-message {
  background: url("../../assets/images/dc.png") no-repeat;
  width: 20px;
  height: 20px;
}

::v-deep .el-icon-my-message:before {
  content: "替";
  font-size: 20px;
  visibility: hidden;
}

::v-deep .el-icon-my-message {
  font-size: 18px;
}

::v-deep .el-icon-my-message:before {
  content: "\e611";
}

::v-deep .el-icon-my-add {
  background: url("../../assets/images/addPaper.png") no-repeat;
  width: 20px;
  height: 20px;
}

::v-deep .el-icon-my-add:before {
  content: "替";
  font-size: 20px;
  visibility: hidden;
}

::v-deep .el-icon-my-add {
  font-size: 18px;
}

::v-deep .el-icon-my-add:before {
  content: "\e611";
}

.header-ul {
  list-style: none;
  display: flex;

  li {
    width: 115px;
    height: 164px;
    text-align: center;
    background: #f6f8fc;
    margin-left: 12px;

    img {
      margin-top: 34px;
    }

    p {
      margin-top: 6px;
    }
  }
}

.sjform-tip {
  width: 100%;
  height: 46px;
  background: #fffbe8;
  border-radius: 4px;
  line-height: 46px;
  color: #ed6a0c;
  box-sizing: border-box;
  padding-left: 16px;
}
</style>
